import React, { useState, useEffect } from 'react';
import {
    Modal,
    Descriptions,
    Tag,
    Spin,
    message
} from 'antd';
import moment from 'moment';
import { request } from 'umi';

// 获取场地预约套餐详情
const fetchPackageDetail = async (id) => {
    return request(`/api/v1/venue/package/${id}`, {
        method: 'GET',
    });
};

/**
 * 场地预约套餐详情弹窗组件
 * @param {object} props - 组件属性
 * @param {boolean} props.visible - 弹窗是否可见
 * @param {function} props.onCancel - 关闭弹窗的回调函数
 * @param {number} props.packageId - 当前套餐的ID
 * @param {Array} props.stores - 所有门店列表
 * @param {Array} props.venues - 所有场地列表
 * @returns {JSX.Element} - 渲染的组件
 */
const PackageDetail = ({ visible, onCancel, packageId, stores, venues }) => {
    const [loading, setLoading] = useState(false);
    const [currentPackage, setCurrentPackage] = useState(null);

    useEffect(() => {
        if (packageId && visible) {
            const loadDetail = async () => {
                try {
                    setLoading(true);
                    const res = await fetchPackageDetail(packageId);
                    if (res.success) {
                        const packageData = res.data;

                        // 处理门店ID，转换为门店对象
                        const storeObjects = [];
                        try {
                            if (packageData.stores) {
                                const storeIds = JSON.parse(packageData.stores);
                                storeIds.forEach(storeId => {
                                    const store = stores.find(s => s.id === storeId);
                                    if (store) {
                                        storeObjects.push(store);
                                    }
                                });
                            }
                        } catch (e) {
                            console.error('解析门店ID出错:', e);
                        }

                        // 处理场地ID，转换为场地对象
                        const venueObjects = [];
                        try {
                            if (packageData.venues) {
                                const venueIds = JSON.parse(packageData.venues);
                                venueIds.forEach(venueId => {
                                    const venue = venues.find(v => v.id === venueId);
                                    if (venue) {
                                        const store = stores.find(s => s.id === venue.store_id);
                                        const storeName = store ? store.name : '未知门店';
                                        venueObjects.push({
                                            ...venue,
                                            storeName
                                        });
                                    }
                                });
                            }
                        } catch (e) {
                            console.error('解析场地ID出错:', e);
                        }

                        packageData.storeObjects = storeObjects;
                        packageData.venueObjects = venueObjects;

                        setCurrentPackage(packageData);
                    } else {
                        message.error(res.message || '获取场地预约套餐详情失败');
                    }
                } catch (error) {
                    console.error('获取场地预约套餐详情出错:', error);
                    message.error('获取场地预约套餐详情失败');
                } finally {
                    setLoading(false);
                }
            };
            loadDetail();
        } else {
            // 关闭弹窗时清空数据
            setCurrentPackage(null);
        }
    }, [packageId, visible, stores, venues]);

    return (
        <Modal
            title="场地预约套餐详情"
            visible={visible}
            onCancel={onCancel}
            footer={null}
            width={700}
            destroyOnClose
        >
            <Spin spinning={loading}>
                {currentPackage && (
                    <Descriptions bordered column={2}>
                        <Descriptions.Item label="套餐名称" span={2}>{currentPackage.name}</Descriptions.Item>
                        <Descriptions.Item label="套餐价格">{`¥${(currentPackage.price).toFixed(2)}`}</Descriptions.Item>
                        <Descriptions.Item label="使用时长">{`${currentPackage.duration}小时`}</Descriptions.Item>
                        <Descriptions.Item label="状态">
                            <Tag color={currentPackage.status === 1 ? 'green' : 'red'}>
                                {currentPackage.status === 1 ? '启用' : '禁用'}
                            </Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="排序">{currentPackage.sort_order}</Descriptions.Item>
                        <Descriptions.Item label="创建时间" span={2}>
                            {currentPackage.created_at ? moment(currentPackage.created_at * 1000).format('YYYY-MM-DD HH:mm:ss') : '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="套餐描述" span={2}>
                            {currentPackage.description || '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="适用门店" span={2}>
                            {currentPackage.storeObjects && currentPackage.storeObjects.length > 0 ? (
                                <div>
                                    {currentPackage.storeObjects.map((store) => (
                                        <Tag color="blue" key={store.id} style={{ marginBottom: '5px' }}>
                                            {store.name}
                                        </Tag>
                                    ))}
                                </div>
                            ) : '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="适用场地" span={2}>
                            {currentPackage.venueObjects && currentPackage.venueObjects.length > 0 ? (
                                <div>
                                    {currentPackage.venueObjects.map((venue) => (
                                        <Tag color="green" key={venue.id} style={{ marginBottom: '5px' }}>
                                            {venue.storeName} - {venue.name}
                                        </Tag>
                                    ))}
                                </div>
                            ) : '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="可用星期" span={2}>
                            {currentPackage.available_weekdays ? JSON.parse(currentPackage.available_weekdays).map(day => `周${['一', '二', '三', '四', '五', '六', '日'][day - 1]}`).join(', ') : '-'}
                        </Descriptions.Item>
                        <Descriptions.Item label="可用时间段" span={2}>
                            {currentPackage.available_times ? JSON.parse(currentPackage.available_times).map(t => `${t.start} - ${t.end}`).join(', ') : '-'}
                        </Descriptions.Item>
                    </Descriptions>
                )}
            </Spin>
        </Modal>
    );
};

export default PackageDetail;